<template>
  <div class="u-page">
    <!-- 顶部按钮 -->
    <div class="u-sticky u-flex u-row-between u-box u-bcl-white">
      <div class="u-cl-content u-pointer" @click="goBack">取消</div>
      <div class="u-cl-primary u-pointer" @click="save">保存</div>
    </div>

    <div class="u-box">
      <!-- 标题 -->
      <div class="u-mb-15 u-mt-15">
        <div class="u-fz-26 u-font-bold">
          {{ info.title }}（{{ isSelectList.length }}/{{ maxlength }}）
        </div>
        <div class="u-pb-10 u-pt-10 u-cl-content">{{ info.tips }}</div>
      </div>

      <!-- 选项列表 -->
      <ul>
        <li
            class="u-inline u-pointer"
            v-for="(item, index) in list"
            :key="index"
            @click="selectItem(item)"
        >
          <u-tag
              :text="item.label"
              :type="item.isSelect ? 'primary' : 'info'"
              :mode="item.isSelect ? 'light' : 'dark'"
          ></u-tag>
        </li>

        <!-- 添加标签按钮 -->
        <li class="u-inline">
          <div class="u-center add-btn u-pointer" @click="visible1 = true">
            <div class="u-mr-5">
              <u-icon class="u-cl-primary" name="plus"></u-icon>
            </div>
            <div class="u-cl-primary">自定义</div>
          </div>
        </li>
      </ul>
      <div style="margin: 10px"><br></div>
    </div>

      <!-- 添加固定标签 add 20210719 -->
	  <div class="u-pt-20">
	  	<div class="u-title u-flex u-row-between u-col-center u-mb-10 border-bottom">
	  	  <div class="u-flex u-col-center u-flex-1">
	  	    <div class="job-name u-mb-5">
	  	      热门标签
	  	    </div>
	  	  </div>
	  	</div>
	  	<ul v-for="(item, index) in hotList">
	  	  <div class="tag-title">{{item.tagName}}</div>
	  	  <li
	  	      class="u-inline u-pointer"
	  	      v-for="(citem, cindex) in item.destags"
	  	      :key="cindex"
	  	      @click="selectHotItem(citem)"
	  	  >
	  	    <u-tag
	  	        :text="citem.label"
	  	        :type="citem.isSelect ? 'primary' : 'info'"
	  	        :mode="citem.isSelect ? 'light' : 'dark'"
	  	    ></u-tag>
	  	  </li>
	  	</ul>
	  </div>

    <!-- 添加自定义标签 -->
    <u-modal
        ref="uModal"
        title="添加自定义标签"
        show-cancel-button
        async-close
        @confirm="addTag"
        v-model="visible1"
    >
      <div class="u-p-20">
        <u-form :model="form" ref="uForm">
          <u-form-item label="名称" label-position="top">
            <u-input v-model="form.key1" placeholder="请填写标签，符号无效"></u-input>
          </u-form-item>
        </u-form>
      </div>
    </u-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: {},
      modes: {
        1: {
          title: "关键字",
          tips: "建议您从推广内容中提取关键字，有助于增加活动的推广力度",
        },
      },
      list: [],
      maxlength: 1000,

      form: {
        key1: "",
      },

      visible1: false,
      hotList: []
    };
  },

  async onLoad() {
    this.info = this.modes[this.$query.mode || 1];
    
    await this.getTagList();
    await this.initHotTagList();// add 20210719

    // 已选中的标签回显，我这边的list是定义死的，如果从接口获取的话，记得把这段代码放到请求完毕，list赋值之后
    let prevPageIsSelectList = uni.getStorageSync("prevPageIsSelectList") || [];
    if (this.list.length>0) {
      this.list.forEach((item) => {
        prevPageIsSelectList.forEach((citem) => {
          if (item.value == citem.value) {
            item.isSelect = true;
          }
          // 标签同步选中或者取消---add  20210719
		      this.isExistInHotArr(this.hotList,item,true)
        });
      });
    }

    // 清空
    //uni.setStorageSync("prevPageIsSelectList", []);
    uni.removeStorage("prevPageIsSelectList");

  },

  methods: {
    /**
     * 保存
     */
    save() {
      if (this.isSelectList.length < 3) {
        return this.$u.toast("至少选择3个标签哦~");
      }

      // 保存选中的标签列表
      if(this.$query.mode === "1"){
        uni.$emit("saveTagList", this.isSelectList);
      }
      
      this.goBack();
    },

    /**
     * 添加自定义标签
     */
    async addTag() {
      if (this.form.key1 && this.form.key1.length>2 && !this.hasSpecial(this.form.key1)) {
        // 添加成功
        setTimeout(() => {
          this.list.push({
            label: this.form.key1,
            value: this.form.key1,
            // isSelect: false,
            isSelect: true,// 默认选中
          });
          this.form.key1 = "";
          this.visible1 = false;
          this.$refs.uModal.clearLoading();

          //this.saveTagToDb();
        }, 1000);
      } else {
        if(this.hasSpecial(this.form.key1)){
          this.$u.toast("标签不能包含符号");
        }else{
          this.$u.toast("字数不低于三个字");
        }
        this.$refs.uModal.clearLoading();
      }
    },

    /**
     * 初始化标签
     */
    async getTagList(){
      let prevPageIsSelectList = uni.getStorageSync("prevPageIsSelectList") || [];
      this.list =  prevPageIsSelectList;
    },

    /**
    * 初始化热门标签
    */
    async initHotTagList() {
      const userInfo = uni.getStorageSync('userInfo')
      let result = await this.$u.api.unifyRequest({
        appid: 'OpenTB',
        wf_num: 'R_OpenTB_B003',
          userId: userInfo.userId,
          loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
      });
      if(result.code == '200'){
        this.hotList = result.data
      }
    },

    /**
    * 选中热门标签
    */
	selectHotItem(item) {
		let isSelect = !item.isSelect;
		item.isSelect = isSelect;
		if(this.isExistInArr(this.list,item,'N')){
			this.isExistInArr(this.list,item,isSelect)
		}else{
			this.list.push(item)
		}
	},
	
	/**
	 * 将数组中的某个元素更改为选中/取消状态
	 */
	isExistInArr(arr,item,isSelect) {
		let flag = false
		arr.forEach((titem) => {
			if(item.label == titem.label){
				if(isSelect != 'N'){
					titem.isSelect = isSelect
				}
				flag = true
			}
		})
		return flag
	},
	
	/**
	 * 将数组中的某个元素更改为选中/取消状态(点击个人标签列表)
	 */
	isExistInHotArr(arr,item,isSelect) {
		let flag = false
		arr.forEach((titem) => {
			let childArr = titem.destags
			childArr.forEach((citem) => {
				if(item.label == citem.label){
					if(isSelect != 'N'){
						citem.isSelect = isSelect
					}
					flag = true
				}
			})
		})
		return flag
	},


    /**
     * 选中标签
     */
    selectItem(item) {
      let isSelect = !item.isSelect;
      if(this.$query.mode === "1" || this.$query.mode === "2"){
        if (isSelect && this.isSelectList.length >= this.maxlength) {
          return this.$u.toast("最多选择5个标签哦~");
        } else {
          item.isSelect = isSelect;
        }
      } else {
        item.isSelect = isSelect;
      }
    },

  },

  computed: {
    isSelectList() {
      return this.list.filter((item) => item.isSelect) || [];
    },
  },
};
</script>

<style lang="scss" scoped>
.u-page {
  /deep/ .u-tag {
    &.u-mode-dark-info {
      border: 2rpx solid transparent;
    }
  }

  .add-btn {
    width: 150rpx;
    height: 52rpx;
    font-size: 22rpx;
    margin: 0 10rpx 10rpx 0;
    border: 2rpx dashed $u-type-primary;
  }

  ._span{
    color: #3b79fe;
    margin:5px;
  }
}
</style>
